<template>
  <div>
    <div class="mb-1">
      <el-button
        type="primary"
        size="small"
        class="btn-long"
        @click="handleEdit()"
        icon="el-icon-plus"
      >
        保证合同
      </el-button>

      <el-button
        size="small"
        :loading="refuseLoading"
        class="float-right"
        @click="getData()"
        icon="el-icon-refresh"
      >
        刷新
      </el-button>
    </div>
    <c-table border class="table-sm flex-1" :columns="tableColumns" :data="tableData"></c-table>
    <promise-edit
      :form-data="editData"
      :is-redo="isRedo"
      :table-id="editId"
      :visible.sync="editVisible"
      :related-data="relatedData"
      @success="getData()"
    ></promise-edit>

    <el-dialog
      top="30px"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :visible.sync="contractView"
    >
      <el-tabs>
        <el-tab-pane label="合同信息">
          <pdf-view :contract-id="contractId" :view-mode="true" :query-id="queryId"></pdf-view>
        </el-tab-pane>
        <el-tab-pane label="附件">
          <div v-for="(file, index) of attachData" :key="index">
            <attach-item :attach-data="file"></attach-item>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import contractGuardMixins from './contractGuardMixins'
import { mapGetters } from 'vuex'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
import PromiseEdit from '@/credit/views/county/unionProvince/components/contractApproveDeploy/promise/PromiseEdit'
import { arrayFromString } from '@vimi/utils-tool'
import { deleteOss } from '@/common/api/oss'
import AttachItem from '@/bank/components/attach/Item'
import { attachAdapter } from '@/bank/components/attach/index'

const enumEntityType = {
  1: '法人',
  2: '自然人',
}
export default {
  props: {
    isRedo: {
      // 是否合同重做，
      type: Boolean,
      default: false,
    },
    tableData: {
      type: Array,
      default: () => [],
    },
    queryId: String,
    relatedData: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    PromiseEdit,
    PdfView,
    AttachItem,
  },
  mixins: [contractGuardMixins],
  data() {
    return {
      enumEntityType,
      postData: {},
      saveLoading: false,
      tableName: 'gua_contract',
      editVisible: false,
      editId: '',
      tableColumns: [
        {
          attrs: { label: '保证人类型', prop: 'gua_entity_type', align: 'center' },
          process: v => enumEntityType[v],
        },
        { attrs: { label: '保证人', prop: 'gua_entity', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'gua_entity_mobile', align: 'center' } },
        { attrs: { label: '保证人地址', prop: 'gua_entity_address', align: 'center' } },
        { attrs: { label: '居民身份证/营业执照号', prop: 'gua_entity_cert_no', align: 'center' } },
        { attrs: { label: '签约地点', prop: 'sign_address', align: 'center' } },
        { attrs: { label: '合同编号', prop: 'gua_contract_no', align: 'center' } },
        {
          attrs: { label: '操作', align: 'center', width: 120 },
          operations: [
            {
              content: '查看',
              icon: 'fa fa-search',
              attrs: { class: 'p-0 mx-1' },
              event: this.handleView,
            },
            {
              content: '编辑',
              icon: 'fa fa-edit',
              attrs: { class: 'text-info p-0 mx-2' },
              event: this.handleEdit,
              ifRender: row => +row.sign_status === 0,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger p-0 m-1' },
              event: this.deleteRow,
              ifRender: row => +row.sign_status === 0,
            },
          ],
        },
      ],
      editData: {},
      entityType: 2,
      contractView: false,
      contractId: '',
      attachData: [],
      refuseLoading: false,
    }
  },
  computed: {
    ...mapGetters(['entrustContract']),
    isView() {
      return +this.entrustContract.sign_status > 0
    },
  },
  created() {},
  methods: {
    handleView(p) {
      this.attachData = []
      this.contractId = p.doc_id || ''
      const attachment = arrayFromString(p.attachment).map(url => {
        return attachAdapter({
          attachment: url,
        })
      })
      const cert_attachment = arrayFromString(p.cert_attachment).map(url => {
        return attachAdapter({
          attachment: url,
        })
      })

      this.attachData = [...attachment, ...cert_attachment]
      this.contractView = true
    },
    beforeClose() {
      this.contractView = false
      this.contractId = ''
    },
    handleEdit(row = {}) {
      this.editId = row.gua_contract_id || ''
      this.entityType = row.gua_entity_type || 2
      this.editData = { ...row }
      this.editVisible = true
    },
    getData() {
      this.refuseLoading = true
      this.$store.dispatch('getGuardsData', this.queryId).finally(() => {
        this.refuseLoading = false
      })
    },
    deleteRow(row) {
      const id = row.gua_contract_id
      const attachs = arrayFromString(row.cert_attachment)
      const docId = row.doc_id
      this.$utils
        .msgbox({
          message: `确定删除合同?`,
          beforeClose: () =>
            this.$api
              .relatedDelete(this.$serviceName, {
                masterTableInfo: JSON.stringify({ gua_contract_id: id }),
                masterTableName: 'gua_contract',
                slaveTableName: 'gua_person_list',
              })
              .then(() => {
                // 删除此合同的所有签约任务
                this.$api.deleteDataBody(this.$serviceName, 'task_list', {
                  extra1: docId,
                })
              })
              .finally(() => {
                if (attachs && attachs.length) {
                  deleteOss(attachs)
                }
              }),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.$store.dispatch('getGuardsData', this.queryId)
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
.item-contract {
  min-width: 600px;
}
</style>
